package com.hmall.order.listener;

import com.hmall.common.client.ItemClient;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class SpringRabbitListener {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ItemClient itemClient;
    //设置延时监听
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name ="delay.queue",durable = "ture"),
            exchange = @Exchange(name = "delay.exchange",delayed = "true"),
            key="delay"
    ))
    public void listenDelayQueue(Map<String,Object> msg){

        //根据订单id查询订单，修改订单状态
        String orderId = (String) msg.get("orderId");
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            //查不到订单，异常处理
            log.info("接收到 delay.queue的延迟消息：{}", msg);
        }
        if (order.getStatus()==1){
            order.setStatus(5);
            order.setCloseTime(new Date());
            orderMapper.updateById(order);
            //回滚商品库存
            itemClient.refundItemStock(msg);
        }
    }
}
